<?php

namespace App\Service\Common;

use App\Jobs\Export\Export;
use App\Models\Clickhouse\Guanyuan\GyDailyDeliveryReportCHModel;
use App\Models\Common\FsCompanyModel;
use App\Models\Common\FsCompanyUserMappingModel;
use App\Models\Common\FsCompanyUserModel;
use App\Remote\Rms\RmsUserRemote;
use App\Service\BaseService;
use Carbon\Carbon;
use PhpOffice\PhpSpreadsheet\IOFactory;

class AnalyzeXlsxService extends BaseService
{
    public static function logic($file, $source): string
    {
        $msg = '';
        switch ($source) {
            case 'importSupplierCruiseStaff':
                self::ImportSupplierCruiseStaff($file);
                $msg = '服务商员工正在导入,请稍后刷新查看';
                break;
        }
        return $msg;
    }

    public static function ImportSupplierCruiseStaff($file)
    {
        $spreadsheet = IOFactory::load($file);

        // 第一行校验
        $firstRowValidate = [
            'A' => '姓名',
            'B' => '手机号',
            'C' => '服务商',
        ];

        // 获得品控供应商
        $departmentIdSupplierMapping = [];
        $companyIdSupplierMapping    = [];
        FsCompanyModel::query()
            ->where('organizationId', 100)
            ->select(['id', 'organizationId', 'departmentId', 'name'])
            ->chunkById(100, function ($fsCompanyList) use (&$departmentIdSupplierMapping, &$companyIdSupplierMapping) {
                foreach ($fsCompanyList as $fsCompanyItem) {
                    $departmentIdSupplierMapping[$fsCompanyItem->departmentId] = $fsCompanyItem->name;
                    $companyIdSupplierMapping[$fsCompanyItem->id]              = $fsCompanyItem->name;
                }
            });

        // 列范围
        $cellColumnRadius = array_keys($firstRowValidate);

        // 获得数据
        $data = [];

        // 遍历第一个sheet中的所有单元格
        foreach ($spreadsheet->getWorksheetIterator() as $worksheet) {
            // 循环每一行
            foreach ($worksheet->getRowIterator() as $row) {
                $firstRowValidateRes = [];
                // 第一行校验
                if ($row->getRowIndex() == 1) {
                    foreach ($row->getCellIterator() as $cell) {
                        if (in_array($cell->getColumn(), $cellColumnRadius)) {
                            if ($firstRowValidate[$cell->getColumn()] != $cell->getValue()) {
                                $firstRowValidateRes[] = $cell->getColumn() . '列应为 [' . $firstRowValidate[$cell->getColumn()] . '] 文件是 [' . $cell->getValue() . ']';
                            }
                        }
                    }

                } else {
                    // 组数据

                    // 列的key
                    $columnDataKey = [
                        'A' => 'username',
                        'B' => 'mobile',
                        'C' => 'fsCompanyName',
                    ];
                    foreach ($row->getCellIterator() as $cell) {
                        if ($cell->getColumn() == 'A' && $cell->getValue() == null) {
                            unset($data[$row->getRowIndex()]);
                            continue 2;
                        }
                        if ($cell->getColumn() == 'B') {
                            if ($cell->getValue() == null) {
                                $firstRowValidateRes[] = $cell->getColumn() . '列' . $row->getRowIndex() . '行的手机号为空';
                            } elseif (!preg_match("/^1\d{10}$/", $cell->getValue())) {
                                $firstRowValidateRes[] = $cell->getColumn() . '列' . $row->getRowIndex() . '行的手机号格式错误';
                            }
                        }
                        if ($cell->getColumn() == 'C' && !in_array($cell->getValue(), $departmentIdSupplierMapping)) {
                            $firstRowValidateRes[] = $cell->getColumn() . '列' . $row->getRowIndex() . '行的品控服务商未建档，请联系相关负责人';
                        }

                        if (in_array($cell->getColumn(), $cellColumnRadius)) {
                            $data[$row->getRowIndex()][$columnDataKey[$cell->getColumn()]] = (string)$cell->getValue();
                        }
                    }
                }
                // 抛出错误
                if (count($firstRowValidateRes)) {
                    BaseService::throwErr(implode(',', $firstRowValidateRes), 400);
                }
            }
            break; // 只要第一个
        }

        // 查询用户信息 新增关联
        dispatch(function () use ($data, $companyIdSupplierMapping) {
            collect($data)->chunk(200)->map(function ($mobileSplit) use ($companyIdSupplierMapping) {
                // RMS 请求
                $response = RmsUserRemote::importSupplierCruiseStaff(collect($mobileSplit)->values()->toArray());

                foreach ($response as $userItem) {
                    $fsCompanyId           = (int)array_search($userItem['fsCompanyName'], $companyIdSupplierMapping);

                    if ($fsCompanyId == 0) {
                        continue;
                    }

                    FsCompanyUserModel::query()
                        ->updateOrCreate([
                            'rmsUserId'              => $userItem['userId'],
                            'name'                   => $userItem['username'],
                            'phone'                  => $userItem['mobile'],
                            'source'                 => FsCompanyUserModel::SOURCE_QUALITY_CONTROL,
                            'ext'                    => FsCompanyUserModel::EXT_OUT,
                        ]);

                    FsCompanyUserMappingModel::query()
                        ->updateOrCreate([
                            'fsCompanyId' => $fsCompanyId,
                            'rmsUserId'   => $userItem['userId'],
                            'feishuId'    => '',
                        ]);
                }
            });
        });
    }


}
